Skip to content

[PR] fix(loop): a failed compress must not kill the task — feed the model a recovery receipt instead of ending the turn - #5231

Merged
ranxianglei merged 7 commits into
masterfrom
2026-11-01_failed-compress-receipt-retry
Oct 31, 2026
Merged

ranxianglei merged 7 commits into
masterfrom
2026-11-01_failed-compress-receipt-retry

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

fix(loop): a failed compress must not kill the task — feed the model a recovery receipt instead of ending the turn

Fixes #5179 (and the same class of silent task deaths on every protocol wire). Companion gate tests included.

What was broken

From v0.1.209, one failed call of the built-in compress tool (any reason: bad refs, sub-viability range, malformed args) ended the whole user turn. Clients saw a bare "Compression FAILED..." message and nothing more — whatever task the model was in the middle of just stopped. No error, no continuation, no visible retry. On Anthropic clients the reported stop_reason wasn't even a legal Anthropic value (length), which is what #5179 captured.

Why

#4186 (first shipped in v0.1.209) ended the turn on the first failed-only mutating round, so that round's ephemeral failure frames could never ride an internal re-request upstream and rewrite a frozen provider prefix (cache seam, see #1548). The motivation is sound and stays. The mistake is the consequence: ending the turn with a synthetic finish_reason: "length" — which no OpenAI-protocol client resumes (OpenAI length ≠ "keep going"; auto-continue is Anthropic max_tokens semantics only), so the task dies at exactly the moment the context tool hiccuped. The failure rate is not zero in practice: refs go stale when acp_status output lags, JSON truncation happens under output limits, and there are many such call shapes — so "failed compress" is a routine event, not a rare edge.

What changed (2 commits)

1. fix(#5179): map the loop's early "length" finish onto Anthropic's max_tokens (re-applied here after the #5211 revert removed it)
The one remaining wire-level illegality: Anthropic stop_reason: "length" does not exist. Early/loop-end completions now surface as max_tokens, the value Anthropic clients know means "go on".

2. fix(loop): ...recovery receipt... (#5220) — the actual contract change
A failed-only round no longer ends the turn when the client can be shown the failure:

  • the failing calls' ephemeral tool frames (tool_call + tool_result) are dropped from the internal rebuild body — they never touch the upstream, #1548/#4186's seam invariant holds byte-for-byte;
  • an assistant message carrying exactly the ❌ …Compression FAILED… receipt lines already streamed to the client is appended;
  • the loop fires its normal re-request. The model reads back its own failed attempt plus the reason ("No eligible message ranges are available now; continue the task without compressing…") and continues the real work. Because those receipt bytes were already delivered to the client, the client's next request carries them identically — the provider-side prefix is untouched.

Guards, unchanged-in-effect:

  • an identical (name, args) signature failing again still ends the turn (the #156 signature breaker, restored around the new path);
  • threadContinue sessions and marker-off surfaces (visibilityMarkers=false) keep the old length-break fallback, because in those channels the client can't be handed the receipt bytes and a receipt-only re-request would reintroduce server-side invisible bytes.

Evidence

  • New gate suite tests/issue5220-failed-compress-receipt.test.ts: receipt shape lands in the rebuild body while the ephemeral frames stay off it; natural stop end instead of synthetic length; signature-breaker stops the same failing call a second time; distinct failing calls run out against MAX_LOOP_ROUNDS (no unbounded ping-pong); marker-off falls back to the old break.
  • Contract updates in 7 existing suites that pinned the old "one request, no re-request" behavior (loop-core, loop-compress, compress-credit, ccr-v2, issue1195-overflow-refold, issue1502-raw-args-salvage, issue5179-anthropic-early-stop-reason — the last one keeps asserting max_tokens and additionally proves the receipt re-request never carries an ephemeral frame).
  • Full suite: green except config-surface-guard ("every config leaf + CLI flag is documented"), which fails identically on stock origin/master (dcf760753) with my changes stashed — pre-existing, unrelated, flagged here rather than fixed in this PR.
  • Wire-level A/B bench (OpenAI chat wire, anonymous lane, fake model issues one unresolvable-ref compress call):
    • v0.1.209: upstreamRequests=1, final SSE chunk finish_reason:"length" + [DONE] → client stops, task dead.
    • this branch: upstreamRequests=2; round 2 body contains zero tool frames and an assistant message with the exact ❌ Compression FAILED receipt lines; final finish_reason:"stop" → model continues.
  • Cache-seam fuzz family (cache-seam-fuzz etc.): green — the frozen-prefix guarantee #4186 existed for is intact.

Scope / non-goals

Does not change why compress calls fail (stale refs / truncated args) — improving first-attempt success rate is a separate follow-up. Does not touch the plugin (ACP delegate) lane, which runs folds out-of-band and never hits this path.

ework-agent added 2 commits October 30, 2026 15:26
…_tokens

The loop ends a turn early in two places (failed-only compress round
#156/#4186, and the round limit), both with finishReason "length" —
OpenAI's word. The Anthropic wire has no such stop reason, and Claude
Code treats an unknown one as a normal end of turn, so the agent stopped
mid-task and waited for the user. Translate to max_tokens at the adapter
boundary: Claude Code auto-resumes a max_tokens turn, which is what an
early end of an unfinished turn wants. Upstream's own stop reasons pass
through unchanged.
…e-requests instead of ending the turn with "length" (#5220)

#4186 ended the turn on the first failed-only mutating round so that
round's ephemeral failure frames could never reach upstream. On
OpenAI-protocol clients (and on the Anthropic wire before #5202's
revert) the synthetic finish_reason "length" is not resumed by anyone,
so a single malformed compress call silently killed the user's task —
from v0.1.209 onward.

Contract change: when every failing call in a failed-only round had its
failure receipt streamed to THIS client (visibility markers on, regular
non-thread lane), the ephemeral tool frames are dropped from the rebuild
body, an assistant message carrying byte-for-byte the same receipt lines
the client saw is appended, and the loop's normal re-request fires. The
client then re-sends those exact bytes on its next request, so the
upstream prefix is never touched and the model reads back its own failed
attempt plus why it failed and continues the task. The turn still ends
when an identical (name, args) signature fails again (the restored #156
signature breaker), in threadContinue sessions, or on marker-off
surfaces — anywhere the client cannot be handed the receipt bytes.

Tests: new gate suite issue5220-failed-compress-receipt (receipt shape
+ natural end, signature breaker cap, unbounded distinct failures run to
MAX_LOOP_ROUNDS, marker-off fallback); contract updates in loop-core,
loop-compress, compress-credit, ccr-v2, issue1195-overflow-refold,
issue1502-raw-args-salvage; issue5179 keeps asserting max_tokens only on
a natural length-end round.
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-11-01_failed-compress-receipt-retry (3ed35a5)

Latest build — install this exact version

npm install -g billion-context@0.0.7408-pr.5231.6a54eaa

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Recent builds (commit → version)

commit version build
3ed35a5 billion-context@0.0.7408-pr.5231.6a54eaa build
4f2fcd1 billion-context@0.0.7333-pr.5231.93ba79e build
b5f2e21 billion-context@0.0.7208-pr.5231.7335e94 build
ce27617 billion-context@0.0.7169-pr.5231.f2fa50b build
92548e1 billion-context@0.0.7073-pr.5231.8682680 build

Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr5231.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei ranxianglei changed the title fix(loop): a failed compress must not kill the task — feed the model a recovery receipt instead of ending the turn [PR] fix(loop): a failed compress must not kill the task — feed the model a recovery receipt instead of ending the turn Oct 30, 2026
ci-sync added 2 commits October 30, 2026 21:48
… under the global legacy test baseline its sidecar never opens and the index reconstruction gate can never pass
… upstream (#5220 review)

Review of the #5220 receipt-retry path found one degenerate state: when EVERY
failure marker of a failed-only round was already streamed in an earlier round
(seenMarkers dedup — identical failure text, different args, e.g. two equal-size
ranges both failing "Total compressible content too small"), streamedMarkers is
empty and the code pushed a zero-byte assistant message into the re-request
body. On strict wires (Anthropic) an empty text block is an illegal frame; on
every wire it is a meaningless zero-byte turn. Reproduced deterministically:
session with two 4-char messages, compress m00001..m00001 then m00003..m00003 →
round-2 marker deduped → empty assistant item observed in the second
re-request body.

Skip the receipt push when there are no new marker bytes: the body degrades to
history + this round's prose, stays cache-clean (nothing server-invisible rides
upstream), and the restored signature breaker / MAX_LOOP_ROUNDS bound any
resulting ping-pong.

Tests: T6 in tests/issue5220-failed-compress-receipt.test.ts pins the edge
(negative control verified — fails on the pre-fix head with exactly the
zero-byte assertion); new threads-continue fallback test in
tests/issue5179-anthropic-early-stop-reason.test.ts covers the last untested
receiptable-guard branch (break without re-request, still max_tokens).
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

查重: 不重复 — 本 PR 是 #5220(分析 issue)的实现,Fixes #5179(症状报告);同家族但机制/路径不同的在途条目:#5100(preflight 中断重试时保留 recovery receipt,走的是 preflight 路径而非 loop 的 failed-only round 路径)——两者不冲突,后续可对照确认 receipt 语义一致。背景链条 #4186/#1548(seam 不变量的来源)、#5211(revert,本 PR 重新应用了其中的 stop_reason 映射)均已在 PR 描述中交代。

标签: bug, claude-code, pi, dsh, scope/wiring, p2(失败 compress = 常规事件导致整个回合静默死亡;有绕行——用户重发即可续上,会话状态不丢,故定 p2 而非 p1)。

开始审核:先核对分支代码与 CI 状态,结论按结构化八问给出。

@ranxianglei ranxianglei left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

审查完成(本地分支 @3ed35a5f,已核对 src 全量 diff + 门控套件 + seam 族)。结论:代码通过,无阻塞项;CI 全绿即可人工合并。

逐项核验:

  1. stop_reason 映射(adapter-anthropic.ts):!reason → end_turn 精确保持旧默认;length → max_tokens 对 Anthropic 面语义正确(真正的上游截断在该面本就该报 max_tokens,不存在误伤)。新测试同时钉住「早停=max_tokens」与「重试体零临时帧」。✓
  2. 收据字节一致性(core.ts):streamedMarkers 在 emitMarker 当场收集(而非事后从 seenMarkers 重建)——注释把「为什么不能事后重建」说透了,这是对的决策;dropIds 的 ID 格式与帧发射处逐字一致(core.ts:1365/1375 ↔ 1580/1581),临时帧确实出不了上游。#1548/#4186 缝不变量由 cache-seam fuzz 族背书。✓
  3. 双重有界:窄版 #156 签名断路器(当轮所有签名皆见过才 break)+ MAX_LOOP_ROUNDS=10。#3302 探测族(每次换 args 枚举 ref)行为不变、受界;probeFailures 注释同步改写准确。✓
  4. fallback 通道:threadContinue 与 visibilityMarkers=false 保留旧 length-终止(理由正确:这些通道给不出收据字节,只收据重试会引入服务端不可见字节=正是 #4186 禁止的缝),且日志带具体原因分支。✓
  5. 去重边沿(b5f2e213):整轮标记全部被去重时不收 0 字节收据(strict wire 拒空文本块),改走「无收据重试」,仍受断路器/MAX_LOOP_ROUNDS 双界——T6 钉死。✓
  6. failedCallSignature:顶层键排序归一 + 不可解析回退原始字节,取 pr.arguments(原始模型字节,与 #3661/#156 同源),导出到 loop/index.ts 供测试。✓

非阻塞备注(无需改动):

  • 签名只在 failed-only 分支登记:混合轮里的失败不进 failedSigs,混合→failed-only 的重放检测不跨形状触发;但这类 ping-pong 仍被 MAX_LOOP_ROUNDS=10 兜死,语义可接受。
  • 分支落后 master 4 commit(#4125 启动层修复):已核对其文件集(launcher/listen-policy/port-owner/server)与本 PR 零重叠,GitHub mergeable=MERGEABLE,不构成同步阻塞。
  • ce27617(plugin-fork 测试)实为注释澄清:unified-full pin 早已存在,commit 只是把「为什么必须 pin」写清。无害。
  • body 诚实标注 config-surface-guard 在裸 master 上同样红(stash 验证)——与我在这台机器上跑 master 基线的经验一致,非本 PR 责任。

本地验证(正式全量留给远程 CI,当前 head 轮 queued):

  • 定向批 140/140 绿:issue5220 门控套件、issue5179、loop-core、loop-compress、compress-credit、ccr-v2、issue1195、issue1502、plugin-fork + cache-seam-fuzz / responses-fold / responses-refold / abort-rewind seam 族
  • tsc --noEmit exit 0
  • 无 kernel 改动 ⇒ 不触发 kernel-guard、无需版本 bump ✓

合并后建议留意一个行为面变化:所有协议面上「failed-only 轮」从静默死回合变为最多再试若干轮(≤10)才收尾——这是预期收益(任务不再莫名断),但若线上看到个别 lane 上游请求数上升,属该特性工作证据而非回归。

@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.942-master.71d2494 (rolling master tag).

npm install -g billion-context@0.0.942-master.71d2494  # this exact build
npm install -g billion-context@master  # always the newest merged build

npm view billion-context@master prints the current version at any time.

ranxianglei added a commit that referenced this pull request Oct 31, 2026
…-receipt-pin

[PR] test(loop): pin the pi-subagents fallback channel's failed-compress recovery path (#5231 follow-up)
nexusatemporal pushed a commit to nexusatemporal/billion-context that referenced this pull request Oct 31, 2026
@github-actions github-actions Bot mentioned this pull request Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Claude Code stops mid-task when bili ends a turn early: the Anthropic adapter sends stop_reason "length"

1 participant